var chart;
var last;
var host = window.location.href.substring(7);
var socket = new WebSocket("ws://"+host+"sysinfo");
Highcharts.setOptions({
	global : {
		useUTC : false
	}
});
$(document).ready(function() {
	socket.onmessage = function(event) {
		var x = (new Date()).getTime();
		var y = event.data;
		chart.series[0].addPoint([x, y], true, true);
		console.debug(event.data);
	};
	socket.onopen = function(event) {
		console.debug("Web Socket opened!");
	};
	socket.onclose = function(event) {
		console.debug("Web Socket closed.");
	};

	newChart();
});

function send(message) {
	if (socket.readyState == WebSocket.OPEN) {
		socket.send(message);
	} else {
		console.debug("The socket is not open.");
	}

}

function newChart() {
	chart = new Highcharts.Chart({
		chart : {
			renderTo : 'container',
			defaultSeriesType : 'areaspline',
			marginRight : 10,
		},
		legend: {
	         enabled: false
	    },
	    plotOptions: {
	    	 areaspline: {
	            fillColor: {
	               linearGradient: [0, 0, 0, 300],
	               stops: [
	                  [0, Highcharts.theme.colors[0]],
	                  [1, 'rgba(2,0,0,0)']
	               ]
	            },
	            lineWidth: 1,
	            marker: {
	               enabled: false,
	               states: {
	                  hover: {
	                     enabled: true,
	                     radius: 2
	                  }
	               }
	            },
	            shadow: false,
	            states: {
	               hover: {
	                  lineWidth: 1                  
	               }
	            }
	         }
	      },
		credits: {
            enabled: false
        },
		title : {
			text : 'Live random data'
		},
		xAxis : {
			type : 'datetime',
			tickPixelInterval : 10,
			showLastLabel: true,
			labels: {enabled: false}
		},
		yAxis : {
			title : {
				text : 'Value'
			},
			max: 2000,
			plotLines : [ {
				value : 0,
				width : 1,
				color : '#808080'
			} ]
		},
		tooltip : {
			formatter : function() {
				return '<b>' + this.series.name + '</b><br/>'
						+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)
						+ '<br/>' + Highcharts.numberFormat(this.y, 2);
			}
		},
		exporting : {
			enabled : false
		},
		series : [ {
			name : 'Random data',
			data : (function() {
				// generate an array of random data
				var data = [], time = (new Date()).getTime(), i;

				for (i = -90; i <= 0; i++) {
					data.push({
						x : time + i * 2000,
						y : 1024+Math.random()*100
					});
				}
				return data;
			})()
		} ]
	});
}